package com.diyunapp.xilinapp.me;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.diyunapp.xilinapp.R;
import com.diyunapp.xilinapp.bean.MessageBean;
import com.diyunapp.xilinapp.main.MainActivity;
import com.diyunapp.xilinapp.selfdefine.StatusBarFragmentActivity;
import com.diyunapp.xilinapp.utils.AbDateUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MyMessageActivity extends StatusBarFragmentActivity {

    @Bind(R.id.go_back)
    ImageView goBack;
    @Bind(R.id.message_fresh_lv)
    ListView messageFreshLv;
    @Bind(R.id.message_refresh_view)
    SwipeRefreshLayout messageRefreshView;

    private LayoutInflater inflater;
    private MessageAdapter messageAdapter;
    private List<MessageBean.DataBean> info = new ArrayList<>();
    private View headView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_message);
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        messageAdapter = new MessageAdapter(this);
        ButterKnife.bind(this);
        headView = findViewById(R.id.myco_menubar_inc);
        super.MenuWidget(headView);
        initMessage();
        messageFreshLv.setAdapter(messageAdapter);
        messageRefreshView.setColorSchemeColors(R.color.domain_orange, R.color.green,
                R.color.blue, R.color.yellow);

        messageRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Log.d("zhangxiaoxidebug", "myordersSwiperefreshlayout onRefresh...");
                initMessage();
            }
        });
    }

    private void initMessage() {
        String url = ""+MainActivity.url+"act=goods&op=my_xiaoxi&member_id="+ MainActivity.myLogin.getMemberid()+"";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(10000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        messageRefreshView.setRefreshing(false);
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");

                            if (result == 200) {
                                info.clear();
                                JSONArray listArray = resultObject.optJSONArray("data");
                                Log.i("zhangxiaoxidebug", "listArray=" + listArray);
                                for (int i = 0; i < listArray.length(); i++) {
                                    JSONObject recordObject = listArray.optJSONObject(i);
                                    String message_id=recordObject.optString("message_id");
                                    String message_body = recordObject.optString("message_body");
                                    long message_time = recordObject.optLong("message_time");
                                    info.add(new MessageBean.DataBean(message_id,message_body, message_time));
                                }
                                messageAdapter.setList(info);
                                messageAdapter.notifyDataSetChanged();

                            } else {
                                toast("当前暂无数据");
                                messageRefreshView.setVisibility(View.GONE);

                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();
                            messageRefreshView.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        messageRefreshView.setRefreshing(false);
                        toast("请求失败");
                        messageRefreshView.setVisibility(View.GONE);
                    }
                });
    }

    @OnClick(R.id.go_back)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.go_back:
                finish();
                break;

        }
    }

    class MessageAdapter extends BaseAdapter {
        private List<MessageBean.DataBean> info = new ArrayList<MessageBean.DataBean>();
        private Context context;

        public MessageAdapter(Context context) {
            this.context = context;

        }

        public void setList(List<MessageBean.DataBean> list) {
            this.info = list;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return null == info ? 0 : info.size();
        }

        @Override
        public Object getItem(int position) {
            return null == info ? null : info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (null == convertView) {

                convertView = inflater.inflate(R.layout.item_message, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            MessageBean.DataBean bean= info.get(position);
            viewHolder.messageDetails.setTag(position);
            viewHolder.messageDelete.setTag(position);
            viewHolder.messageContent.setText(bean.getMessage_body());
            viewHolder.messageDate.setText(AbDateUtil.getStringByFormat(bean.getMessage_time()*1000,"yyyy-MM-dd hh:mm:ss"));
            final String message_id=bean.getMessage_id();
            viewHolder.messageDetails.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(MyMessageActivity.this, MessageContentActivity.class);
                    intent.putExtra("message_id", message_id);
                    startActivity(intent);
                }
            });
            viewHolder.messageDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    delete(message_id);
                    info.clear();
                    initMessage();

                }
            });
            return convertView;
        }

        class ViewHolder {
            @Bind(R.id.message_date)
            TextView messageDate;
            @Bind(R.id.message_type)
            TextView messageType;
            @Bind(R.id.message_content)
            TextView messageContent;
            @Bind(R.id.delete_imv)
            ImageView deleteImv;
            @Bind(R.id.message_delete)
            TextView messageDelete;
            @Bind(R.id.message_details)
            TextView messageDetails;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

    private void delete(String message_id) {
        String url = ""+MainActivity.url+"act=goods&op=delxiaoxi&drop_type=msg_system&message_id="+message_id+"&member_id="+MainActivity.myLogin.getMemberid()+"";

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(10000);
        http.send(HttpRequest.HttpMethod.POST, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        bidFreshLv.onRefreshComplete();
                        String resultinfo = responseInfo.result;
                        Log.i("zhangxiaoxidebug", "resultinfo=" + resultinfo);
//                        Logger.e("=================================="+resultinfo);
                        try {
                            JSONObject resultObject = new JSONObject(resultinfo);
                            int result = resultObject.optInt("code");
                            if (result == 200) {
                                String data = resultObject.optString("data");
                               toast(data);


                            } else {
                                toast("当前暂无数据");


                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            toast("查询失败");
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {

                        toast("请求失败");
                        messageRefreshView.setVisibility(View.GONE);
                    }
                });
    }


    public void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
}
